import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_give/common_ui/dialog/dialog_factory.dart';
import 'package:flutter_give/utils/LogUtils.dart';
import 'package:oktoast/oktoast.dart';
import 'package:rapid_kit/rapid_kit.dart';

import '../../theme.dart';

/// 存储卡页面
class MemorycardPage extends StatefulWidget {
  final String deviceId;

  const MemorycardPage({
    super.key,
    required this.deviceId,
  });

  @override
  State<StatefulWidget> createState() {
    return _MemorycardPageState();
  }
}

class _MemorycardPageState extends State<MemorycardPage> {
  late String _deviceId;

  // 指令示例
  late Pipe _pipe;

  // 存储卡状态
  int _total = 0;

  // 剩余可使用
  int _free = 0;

  @override
  void initState() {
    super.initState();
    _deviceId = widget.deviceId;

    LogUtils.w("设备ID${_deviceId}");

    // 创建实例
    _pipe = Pipe.create(_deviceId);
    // 连接设备
    _pipe.establish();

    // _pipe.listen((state) {
    //   LogUtils.w(state);
    //   if (state == PipeState.established) {
    //     // 连接成功建立，可以启动视频播放、发送指令或者其他操作了
    //     _onQuality();
    //   }
    // });

    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Color(0xFFffffff),
      statusBarIconBrightness: Brightness.dark,
    ));

    WidgetsBinding.instance.addPostFrameCallback((_) {
      print("页面渲染完毕");
      _onQuality();
    });
  }

  @override
  void dispose() {
    super.dispose();
    // 销毁实例
    _pipe.abolish();
    _pipe.destroy();
  }

  void _onQuality() async {
    if (!_pipe.isEstablished) return;
    LogUtils.w("========执行=======");
    final resp = await InstructStandard.storageState(_pipe);
    if (!mounted) return;
    if (resp.success) {
      LogUtils.w(resp.data!.total);
      LogUtils.w(resp.data!.free);
      setState(() {
        _total = resp.data!.total;
        _free = resp.data!.free;
      });
    } else {
      showToast("获取画面设置失败");
    }
  }

  Future<bool> _onWillPop() async {
    // HomePageState.globalKeytwo.currentState?.reloadData();
    return true;
  }

  String calculateUsedPercentage(int total, int residue) {
    if (total <= 0) {
      return '0%'; // 如果总数为0或负数，返回0%
    }

    int used = total - residue;
    double percentage = (used / total) * 100;
    int percentageInt = percentage.round(); // 四舍五入到最接近的整数

    return '$percentageInt%';
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
        backgroundColor: Color(0xFFF2F3F5),
        appBar: _buildTitleBar(context),
        body: Padding(
          padding: EdgeInsets.all(16.0), // 这里设置内边距，可以根据需要调整数值
          child: Column(
            children: [
              // 添加本地图片
              Container(
                width: 70, // 宽度撑满
                height: 80, // 高度200
                child: Image.asset(
                  _total > 0 ? 'assets/app_img/memorycard.png' : 'assets/app_img/memorycard_nodata.png', // 根据 _total 的值选择不同的图片// 图片填充方式
                ),
              ),
              SizedBox(height: 10),
              // 添加文字 "事件录像"
              Container(
                padding: EdgeInsets.symmetric(vertical: 3, horizontal: 12),
                // 设置内边距
                decoration: BoxDecoration(
                  color: Color(0xFF70DA9D), // 背景颜色
                  borderRadius: BorderRadius.circular(20), // 设置圆角
                ),
                child: Text(
                  '事件录像',
                  style: TextStyle(
                    color: Colors.white, // 字体颜色
                    fontSize: 12, // 字体大小
                    // fontWeight: FontWeight.bold, // 字体加粗
                  ),
                ),
              ),
              SizedBox(height: 30),
              _buildreportRow(),
              Spacer(),
              _buildLogoutButton(),
              SizedBox(height: 20),
            ],
          ),
        ),
      ),
      onWillPop: _onWillPop,
    );
  }

  Widget _buildreportRow() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white, // 设置白色背景
        borderRadius: BorderRadius.circular(12.0), // 设置圆角
        border: Border.all(
          color: Color(0xFFf8f7f7), // 设置边框颜色
          width: 1.0, // 设置边框宽度
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05), // 设置阴影颜色
            offset: Offset(0, 2), // 设置阴影偏移量
            blurRadius: 4.0, // 设置阴影模糊半径
            spreadRadius: 0.0, // 设置阴影扩散半径
          ),
        ],
      ),
      padding: EdgeInsets.only(
        top: 5, // 上边距
        bottom: 5, // 下边距
        left: 5, // 左边距
        right: 5, // 右边距
      ),
      child: Column(
        children: [
          // 第一行：0°
          InkWell(
            onTap: () {},
            child: Container(
              padding: EdgeInsets.all(8.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '存储卡状态',
                    style: TextStyle(fontSize: 16),
                  ),
                  Text(
                    _total == -1
                        ? 'SD卡错误'
                        : _total == 0
                            ? '无SD卡'
                            : _total > 0
                                ? '正常'
                                : _total == -2
                                    ? 'SD卡只读'
                                    : _total == -3
                                        ? '正在格式化'
                                        : _total == -4
                                            ? '正在初始化'
                                            : '--',
                    style: TextStyle(fontSize: 15),
                  ),
                ],
              ),
            ),
          ),
          SizedBox(height: 20),
          // 第二行：180°
          InkWell(
            onTap: () {},
            child: Container(
              padding: EdgeInsets.all(8.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '使用空间',
                    style: TextStyle(fontSize: 16),
                  ),
                  Text(
                    _total < 0 ? "--" : calculateUsedPercentage(_total, _free),
                    style: TextStyle(fontSize: 15),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 格式化存储卡
  Widget _buildLogoutButton() {
    return SizedBox(
      width: 270, // 设置按钮宽度为400
      height: 45, // 设置按钮高度为40
      child: ElevatedButton(
        onPressed: () async {
          DialogFactory.instance.showSDformattingDialog(
              context: context,
              dismissClick: () {},
              confirmClick: () async {
                final resp = await InstructStandard.storageFormat(_pipe);
                if (!mounted) return;
                if (resp.success) {
                  _onQuality();
                  _total = 0;
                  showToast("重置成功");
                }
              });
        },
        style: ElevatedButton.styleFrom(
          backgroundColor: Color(0xFFfc3d49),
          foregroundColor: Color(0xFFfc3d49),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(30),
          ),
          padding: const EdgeInsets.symmetric(horizontal: 80),
          // 调整水平内边距
          elevation: 0,
          shadowColor: Colors.transparent,
        ),
        child: const Text(
          '格式化存储卡',
          style: TextStyle(fontSize: 16, color: Color(0xFFffffff)),
          textAlign: TextAlign.center, // 确保文字居中
        ),
      ),
    );
  }

  // 导航
  AppBar _buildTitleBar(BuildContext context) {
    return AppBar(
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios),
        onPressed: () {
          _onWillPop();
          Navigator.of(context).pop();
        },
      ),
      automaticallyImplyLeading: false,
      title: Text(
        "存储卡",
        style: TextStyle(
          fontSize: 17,
          fontFamily: "PingFang SC",
          fontWeight: FontWeight.w600,
        ),
      ),
      centerTitle: true,
    );
  }
}
